package second.linkedlist;

public class Solution07 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = 0;
        int lenB = 0;
        ListNode p = headA;
        while (p != null) {
            p = p.next;
            lenA++;
        }
        p = headB;
        while (p != null) {
            p = p.next;
            lenB++;
        }
        if (lenB > lenA) {
            p = headB;
            headB = headA;
            headA = p;
        }
        int len = Math.abs(lenA - lenB);
        while (len-- > 0) {
            headA = headA.next;
        }
        while (headA != null && headB != null) {
            if (headA == headB) return headA;
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
}
